package com.soft.javase.day15.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;


/**
 * @author yzh
 * @desc TODO
 * @date 2025/5/27
 */
public class CalculatorLogImpl {
    private Calculator target;

    public CalculatorLogImpl(Calculator target) {
        this.target = target;
    }

    public Calculator getProxy() {
        Calculator proxy = null;
        ClassLoader classLoader = target.getClass().getClassLoader();
        Class<?>[] interfaces = target.getClass().getInterfaces();
        InvocationHandler handler = new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws InvocationTargetException, IllegalAccessException {
                System.out.println("日志: the method " + method.getName() + " begin with[" + args[0] + ", " + args[1] + "]");

                Object result = method.invoke(target, args);

                System.out.println("日志: the method " + method.getName() + " end with " + result);

                return result;
            }
        };
        proxy = (Calculator)Proxy.newProxyInstance(classLoader, interfaces, handler);
        return proxy;
    }
}